home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / ptv1n1.arc / L1.C < prev    next >
Text File  |  1990-06-08  |  1KB  |  46 lines

  1. /*
  2.  * *** Listing 1 ***
  3.  *
  4.  * Program to calculate the 16-bit checksum of all bytes in the
  5.  * specified file.  Obtains the bytes one at a time via read(),
  6.  * letting DOS perform all data buffering.
  7.  */
  8. #include <stdio.h>
  9. #include <fcntl.h>
  10.  
  11. main(int argc, char *argv[]) {
  12.    int Handle;
  13.    unsigned char Byte;
  14.    unsigned int Checksum;
  15.    int ReadLength;
  16.  
  17.    if ( argc != 2 ) {
  18.       printf("usage: checksum filename\n");
  19.       exit(1);
  20.    }
  21.  
  22.    if ( (Handle = open(argv[1], O_RDONLY | O_BINARY)) == -1 ) {
  23.       printf("Can't open file: %s\n", argv[1]);
  24.       exit(1);
  25.    }
  26.  
  27.    /* Initialize the checksum accumulator */
  28.    Checksum = 0;
  29.  
  30.    /* Add each byte in turn into the checksum accumulator */
  31.    while ( (ReadLength = read(Handle, &Byte, sizeof(Byte))) > 0 ) {
  32.       Checksum += (unsigned int) Byte;
  33.    }
  34.  
  35.    if ( ReadLength == -1 ) {
  36.       printf("Error reading file %s\n", argv[1]);
  37.       exit(1);
  38.    }
  39.  
  40.    /* Report the result */
  41.    printf("The checksum is: %u\n", Checksum);
  42.  
  43.    exit(0);
  44. }
  45.  
  46.